<template>
  <div class="flex h-full">
    <a-card class="mr-2" :body-style="{ height: '100%', display: 'flex', flexDirection: 'column' }">
      <PatientListDrawer
        :patient-list="dataSource"
        :loading="loading"
        :border-bottom="false"
        :selected-item="store.currentPatient"
        :search-show="true"
        @scroll="onScroll"
        @select="onSelectPatient"
        @refresh="getData()"
      >
        <template #search>
          <a-input-search
            v-model:value="searchParams.searchKey"
            class="w-full mx-1"
            placeholder="床位号/姓名/助记码"
            @search="getData()"
            @change="onInputChange"
          />
        </template>
        <template #tabRadio>
          <a-radio-group v-model:value="store.radioKey" button-style="solid" class="w-full px-3" @change="getData()">
            <a-radio-button :value="0" class="w-1/2 text-center">在院</a-radio-button>
            <a-radio-button :value="1" class="w-1/2 text-center">已出院</a-radio-button>
          </a-radio-group>
        </template>
      </PatientListDrawer>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <PatientInfoHeader :patient-info="store.currentPatient" @change="getData()">
        <template #prefix>
          <div class="text-2xl pr-4 text-primary font-semibold min-w-10">{{ store.currentPatient?.lastBedCode || '- ' }}床</div>
        </template>
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue label="住院科室" :width="200" :value="store.currentPatient.ksmc" />
            <LabelValue label="住院号" :width="220" :value="store.currentPatient.admissionCode" />
            <AllergyHistory
              class="mr-2"
              :width="260"
              :value="store.currentPatient.brGms"
              :patient-info="store.currentPatient"
              @success="(e) => (store.currentPatient.brGms = e)"
            />
            <!-- <LabelValue label="过敏史"labelClass="w-16"  :width="200" :value="store.currentPatient.brGms" /> -->
            <LabelValue label="付费方式" :width="200" :value="store.currentPatient.paymentTypeName" />
            <LabelValue label="住院天数" :width="160" :value="store.currentPatient.zyts" />
          </div>
          <div class="flex items-center">
            <LabelValue label="住院病区" :width="200" :value="store.currentPatient.wardName" />
            <LabelValue label="入区时间" :width="220" :value="store.currentPatient.lastDeptRegTime" />
            <LabelValue label="账户余额" :width="268" :value="formatAmount(store.currentPatient.zhye) + '元'" />
            <LabelValue label="入院诊断" class="mr-2" :width="260" tooltip :value="store.currentPatient.ryzd" />
          </div>
        </div>
      </PatientInfoHeader>
      <div class="flex flex-1 mt-2 overflow-hidden">
        <a-card class="flex-1 overflow-hidden" :body-style="{ padding: '0 8px', height: '100%', overflow: 'hidden' }">
          <TabDoctorAdvice :page-loading="loading" />
        </a-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onUnmounted, ref } from 'vue'
import { debounce } from 'lodash-es'
import { message } from 'ant-design-vue'
import { formatAmount } from '@/utils/format'
import useUserStore from '@/store/user'
import useStore from './store'
import TabDoctorAdvice from './components/TabDoctorAdvice'

const store = useStore()
const { empId } = useUserStore()
const searchParams = ref({
  searchKey: '',
  bqbh: ''
})

const dataSource = ref([])
const loading = ref(false)
const pageNum = ref(1)
const pageSize = ref(20)
const total = ref(0)
const hasMore = ref(true)
const onInputChange = debounce(() => getData(), 300)

// 获取列表数据
const getData = async (isLoadMore = false) => {
  // 如果没有更多数据且是加载更多操作则直接返回
  if (!hasMore.value && isLoadMore) return

  // 如果不是加载更多则重置页码和数据
  if (!isLoadMore) {
    pageNum.value = 1
    dataSource.value = []
  }

  // 防止重复请求
  if (loading.value) return
  loading.value = true

  const {
    code,
    msg,
    data,
    total: totalCount
  } = await post('/inp/zydj/getInpRecordList', {
    statuss: store.radioKey === 0 ? [0, 2] : [1],
    empId,
    bqbh: searchParams.value.bqbh,
    pyjm: searchParams.value.searchKey,
    pageNum: pageNum.value,
    pageSize: pageSize.value
  })
  loading.value = false
  if (code !== 0) return message.error(msg)

  // 更新数据源
  dataSource.value = isLoadMore ? [...dataSource.value, ...data] : data
  total.value = totalCount

  // 判断是否还有更多数据
  hasMore.value = dataSource.value.length < total.value

  // 处理选中逻辑
  !isLoadMore && handlePatientSelection(data)
}

// 处理病人选中逻辑
const handlePatientSelection = (data) => {
  if (store.currentPatient.inplsh) {
    const index = data.findIndex((item) => item.inplsh === store.currentPatient.inplsh)
    if (index > -1) {
      onSelectPatient(data[index])
    } else {
      data[0] && onSelectPatient(data[0])
    }
  } else {
    data[0] && onSelectPatient(data[0])
  }
}

const onSelectPatient = (patient) => {
  store.currentPatient = patient
}
onMounted(() => {
  store.currentPatient = {}
  getData()
})

onUnmounted(() => {
  store.currentPatient = {}
})

// 滚动加载更多
const onScroll = debounce((e) => {
  const { scrollTop, clientHeight, scrollHeight } = e.target
  const scrollDistance = scrollHeight - scrollTop - clientHeight

  // 距离底部100px时加载更多
  if (scrollDistance <= 100 && !loading.value && hasMore.value) {
    pageNum.value++
    getData(true)
  }
}, 100)
</script>
<style lang="less" scoped>
.tabs-disabled {
  cursor: not-allowed;
  filter: opacity(0.5);
  pointer-events: none;
}
:deep(.ant-spin-container) {
  width: 100%;
  height: 100%;
}
:deep(.workstation-tabs) {
  .ant-tabs-tab {
    padding: 12px 32px;
  }
  .ant-tabs-tab + .ant-tabs-tab {
    margin: 0 16px;
  }
  // & > .ant-tabs-nav {
  //   .ant-tabs-tab:nth-child(4) {
  //     position: relative;
  //     &::after {
  //       position: absolute;
  //       top: 0;
  //       right: -16px;
  //       width: 1px;
  //       height: 100%;
  //       background: #f0f0f0;
  //       content: '';
  //     }
  //   }
  // }
  & > .ant-tabs-content-holder {
    height: 100%;
    .ant-tabs-content {
      height: 100% !important;
    }
  }
}
</style>
